package com.str.LLs;
public class DLLOps {

  private DLLNode head, tail;
    
  public DLLOps(DLLNode firstLink, DLLNode lastLink) { 
    head = firstLink;
    tail = lastLink;
  }
     
  public void insert(Object val, DLLNode prior) {
    // Insert elem at a given point in this SLL, either after the node 
    // pred, or before the head node if pred is null.
    DLLNode ins = new DLLNode(val);
    if (prior == null) {         
      ins.next = head;
      head = ins;
      if (tail == null) tail = ins;
      else ins.next.prev = ins;      
    } 
    else {
      ins.next = prior.next;
      prior.next = ins;
      if (prior == tail) tail = ins;
      else ins.next.prev = ins;      
      ins.prev = prior;           
    }
  }

  public void delete(DLLNode del) {
    // Delete node del from this SLL.
    if (del == head) {
      head = head.next;
      if (del == tail) tail = null;
      else head.prev = null;
    } 
    else {
      del.prev.next = del.next;
      if (del == tail) tail = del.prev;
      else del.next.prev = del.prev;
    }
  }

  public DLLNode search(Object val) {
    // Find which (if any) node of this SLL contains an element equal to 
    // target. Return a link to the matching node (or null if there is 
    // none).
    for (DLLNode curr = head; curr != null; curr = curr.next)
      if (val.equals(curr.data))
        return curr;
    return null;
  }

  // Returns the contents of the SLL as a String
  public void print() {       ;
    System.out.print("head");
    for (DLLNode curr = head; curr != null; curr = curr.next)
      System.out.print(" - " + curr.data);
    System.out.println(" - tail");
  }
    
  public static void main(String args[]) {
    String[] word = {"fox", "cow", "pig", "cat", "rat", "lio",
                     "tig", "goa", "dog"};

    DLLNode first, last, temp;
    first = last = new DLLNode(word[0]);
    for (int i=1; i<word.length; i++) {
      temp = new DLLNode(word[i], null, first);
      first.prev = temp;
      first = temp;
    }

    DLLOps dll = new DLLOps(first, last);
 
    System.out.print("Initially DLL: ");
    dll.print();

    temp = dll.search("tig");
    dll.insert("ant", temp);
    System.out.print("insert \"ant\" after \"tig\": ");
    dll.print();
        
    temp = dll.search("cat");
    dll.insert("eag", temp);
    System.out.print("insert \"eag\" after \"cat\": ");
    dll.print();

    temp = dll.search("eag");       
    dll.delete(temp);
    System.out.print("delete value \"eag\": ");
    dll.print();                
  }
}
